# -*- coding: utf-8 -*-
# @Date   : 2019/6/18
# @File   : R23_IC_EnforcementRecordCheck_XD_2D_OTO.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:申请人强制执行、行政处罚记录校验
code:R23_IC_EnforcementRecordCheck_XD_2D_OTO
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d')\
                    for i in range(6)]

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return ""
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float):
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date

# 获取 上次申请时间
def get_relative_date():
    relative_date = ratingRequest.get('relativeDate')
    return Formate(relative_date)

def R23_IC_EnforcementRecordCheck_XD_2D_OTO():
    data = IC_DSJ_2D['data']
    factor = []
    # 强制执行记录
    PCE = getTable(data, 'PCE', 1)
    if PCE is None:
        return u'缺失值'
    elif PCE == "":
        factor.append(1)
    else:
        # 强制执行记录信息单元
        PF03 = getTable(PCE[0], 'PF03', 0)
        if PF03 is None or PF03 == "":
            factor.append(None)
        elif PF03 == [{}]:
            factor.append(1)
        else:
            relativeDate = get_relative_date()
            if relativeDate is None:
                raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
            for i in PF03:
                try:
                    # 强制执行记录信息段
                    PF03A = getTable(i, 'PF03A', 1)
                    if PF03A is None or PF03A == "":
                        factor.append(None)
                    else:
                        # 立案日期(PF03AR01)
                        PF03AR01 = PF03A[0].get('PF03AR01')
                        # 申请执行标的金额
                        PF03AJ01 = PF03A[0].get('PF03AJ01')
                        # 已执行标的金额(PF03AJ02)
                        PF03AJ02 = PF03A[0].get('PF03AJ02')

                        # 限定 立案日期  在上次申请时间到本次申请时间之前
                        if isfloat(PF03AJ01) or isfloat(PF03AJ02):
                            if Formate(PF03AR01) is not None:
                                if relativeDate < Formate(PF03AR01):
                                    if (float(PF03AJ01) if isfloat(PF03AJ01) else float(PF03AJ02)) <= 0:
                                        factor.append(1)
                                    else:
                                        if Formate(PF03AR01) is not None and Formate(PF03AR01) < last_year_list[2]:
                                            factor.append(1)
                                        elif Formate(PF03AR01) is None or (isfloat(PF03AJ01) is False and isfloat(PF03AJ02) is False):
                                            factor.append(0)
                                        elif Formate(PF03AR01) <= last_year_list[0] and Formate(PF03AR01) >= last_year_list[2]:
                                            if (float(PF03AJ01) if isfloat(PF03AJ01) else float(PF03AJ02)) < 6000 and (float(PF03AJ01) if isfloat(PF03AJ01) else float(PF03AJ02)) > 0:
                                                factor.append(1)
                                            else:
                                                factor.append(0)
                                        else:
                                            factor.append(0)
                                else:
                                    factor.append(1)
                            else:
                                factor.append(0)
                        elif PF03AJ01 in null_type_list and PF03AJ02 in null_type_list:
                            factor.append(0)
                except:
                    factor.append(None)
                    continue
        # 行政处罚记录
        PAP = getTable(data, 'PAP', 1)
        if PAP is None:
            return u'缺失值'
        elif PAP == "":
            factor.append(1)
        else:
            # 行政处罚记录信息单元
            PF04 = getTable(PAP[0], 'PF04', 0)
            if PF04 is None or PF04 == "":
                factor.append(None)
            elif PF04 == [{}]:
                factor.append(1)
            else:
                relativeDate = get_relative_date()
                if relativeDate is None:
                    raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
                for i in PF04:
                    try:
                        # 行政处罚记录信息段
                        PF04A = getTable(i, 'PF04A', 1)
                        if PF04A is None or PF04A == "":
                            factor.append(None)
                        else:
                            # 处罚生效日期
                            PF04AR01 = PF04A[0].get('PF04AR01')
                            # 处罚金额
                            PF04AJ01 = PF04A[0].get('PF04AJ01')
                            if isfloat(PF04AJ01):
                                if PF04AR01 == '0000-00':
                                    return 0
                                if Formate(PF04AR01) is not None:
                                    if relativeDate < Formate(PF04AR01):
                                        if float(PF04AJ01) <= 0:
                                            factor.append(1)
                                        else:
                                            if Formate(PF04AR01) is not None and Formate(PF04AR01) < last_year_list[2]:
                                                factor.append(1)
                                            elif Formate(PF04AR01) is None or isfloat(PF04AJ01) is False:
                                                factor.append(0)
                                            elif Formate(PF04AR01) <= last_year_list[0] and Formate(PF04AR01) >= last_year_list[2]:
                                                if float(PF04AJ01) < 6000 and float(PF04AJ01) > 0:
                                                    factor.append(1)
                                                else:
                                                    factor.append(0)
                                            else:
                                                factor.append(0)
                                    else:
                                        factor.append(1)
                                else:
                                    factor.append(0)
                            elif PF04AJ01 in null_type_list:
                                factor.append(0)
                    except:
                        factor.append(None)
                        continue

    factorNotNone = filter(lambda x: x is not None, factor)
    if 0 in factorNotNone:
        return 0
    else:
        return 1
result = R23_IC_EnforcementRecordCheck_XD_2D_OTO()

